package com.travel.travel_springboot_web.service;

import com.travel.travel_springboot_web.entity.Cart;
import com.travel.travel_springboot_web.entity.Goods;
import com.travel.travel_springboot_web.entity.GiftRule;
import com.travel.travel_springboot_web.entity.Order;
import com.travel.travel_springboot_web.entity.OrderGoods;
import com.travel.travel_springboot_web.entity.Address;
import com.travel.travel_springboot_web.mapper.CartMapper;
import com.travel.travel_springboot_web.mapper.GoodsMapper;
import com.travel.travel_springboot_web.mapper.OrderMapper;
import com.travel.travel_springboot_web.mapper.OrderGoodsMapper;
import com.travel.travel_springboot_web.mapper.AddressMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Service
public class CartService {
    
    private static final Logger logger = LoggerFactory.getLogger(CartService.class);
    
    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private GoodsMapper goodsMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    
    @Autowired
    private AddressMapper addressMapper;
    
    @Transactional
    public boolean addToCart(Long userId, Long goodsId, Integer num) {
        try {
            // 1. 检查商品是否存在且上架
            Goods goods = goodsMapper.findById(goodsId);
            if (goods == null || goods.getStatus() != 1) {
                throw new RuntimeException("商品不存在或已下架");
            }
            
            // 2. 检查库存是否足够
            if (goods.getStock() < num) {
                throw new RuntimeException("商品库存不足");
            }
            
            // 3. 检查商品是否已在购物车中
            Cart existingCart = cartMapper.findByUserIdAndGoodsId(userId, goodsId);
            
            if (existingCart != null) {
                // 4. 如果商品已存在，计算新的总数量
                int totalNum = existingCart.getNum() + num;
                
                // 5. 根据新的总数量重新计算赠送数量
                int giftNum = calculateGiftNum(goods.getGiftRules(), totalNum);
                
                // 6. 更新购物车数量和赠送数量
                return cartMapper.updateNumAndGiftNum(existingCart.getId(), userId, totalNum, giftNum) > 0;
            } else {
                // 7. 如果商品不存在，计算赠送数量并新增
                int giftNum = calculateGiftNum(goods.getGiftRules(), num);
                
                // 8. 创建新的购物车项
                Cart cart = new Cart();
                cart.setUserId(userId);
                cart.setGoodsId(goodsId);
                cart.setNum(num);
                cart.setGiftNum(giftNum);
                cart.setSelected(1); // 默认选中
                
                return cartMapper.insert(cart) > 0;
            }
        } catch (Exception e) {
            logger.error("Add to cart failed: ", e);
            throw new RuntimeException("添加购物车失败: " + e.getMessage());
        }
    }
    
    // 计算赠送数量的辅助方法
    private int calculateGiftNum(List<GiftRule> giftRules, int buyNum) {
        if (giftRules == null || giftRules.isEmpty()) {
            return 0;
        }
        
        // 找到适用的最大赠送数量
        int maxGiftNum = 0;
        for (GiftRule rule : giftRules) {
            if (buyNum >= rule.getBuyNum() && rule.getGiftNum() > maxGiftNum) {
                maxGiftNum = rule.getGiftNum();
            }
        }
        
        return maxGiftNum;
    }
    
    public Map<String, Object> getCartList(Long userId) {
        logger.info("Getting cart list for user: {}", userId);
        try {
            List<Cart> cartList = cartMapper.findByUserId(userId);
            logger.info("Found {} items in cart", cartList.size());
            
            // 计算总价和选中商品总价
            BigDecimal totalPrice = BigDecimal.ZERO;
            BigDecimal selectedPrice = BigDecimal.ZERO;
            int totalNum = 0;
            int selectedNum = 0;
            
            // 转换为带有赠送规则的购物车列表
            List<Map<String, Object>> cartItems = new ArrayList<>();
            
            for (Cart item : cartList) {
                // 获取商品信息（包含赠送规则）
                Goods goods = goodsMapper.findById(item.getGoodsId());
                
                // 构建购物车项信息
                Map<String, Object> cartItem = new HashMap<>();
                cartItem.put("id", item.getId());
                cartItem.put("userId", item.getUserId());
                cartItem.put("goodsId", item.getGoodsId());
                cartItem.put("num", item.getNum());
                cartItem.put("selected", item.getSelected());
                cartItem.put("createdAt", item.getCreatedAt());
                cartItem.put("updatedAt", item.getUpdatedAt());
                cartItem.put("goodsTitle", item.getGoodsTitle());
                cartItem.put("goodsImage", item.getGoodsImage());
                cartItem.put("goodsPrice", item.getGoodsPrice());
                cartItem.put("goodsStock", item.getGoodsStock());
                cartItem.put("giftNum", item.getGiftNum());
                cartItem.put("giftRules", goods.getGiftRules());
                cartItem.put("giftRuleText", goods.getGiftRuleText());
                
                cartItems.add(cartItem);
                
                // 计算总价和数量
                BigDecimal itemPrice = BigDecimal.valueOf(item.getGoodsPrice())
                        .multiply(BigDecimal.valueOf(item.getNum()));
                totalPrice = totalPrice.add(itemPrice);
                totalNum += item.getNum();
                
                if (item.getSelected() == 1) {
                    selectedPrice = selectedPrice.add(itemPrice);
                    selectedNum += item.getNum();
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", cartItems);
            result.put("totalPrice", totalPrice);
            result.put("selectedPrice", selectedPrice);
            result.put("totalNum", totalNum);
            result.put("selectedNum", selectedNum);
            
            return result;
        } catch (Exception e) {
            logger.error("Error getting cart list: ", e);
            throw new RuntimeException("Failed to get cart list: " + e.getMessage());
        }
    }
    
    @Transactional
    public boolean updateNum(Long id, Long userId, Integer num) {
        logger.info("Updating cart num: id={}, userId={}, num={}", id, userId, num);
        try {
            if (num < 1) {
                logger.warn("Invalid num: {}, setting to 1", num);
                num = 1;
            }
            
            // 获取购物车项
            Cart cart = cartMapper.findById(id);
            if (cart == null || !cart.getUserId().equals(userId)) {
                return false;
            }
            
            // 检查库存
            Goods goods = goodsMapper.findById(cart.getGoodsId());
            if (goods == null || num > goods.getStock()) {
                throw new RuntimeException("库存不足");
            }
            
            // 计算赠送数量
            int giftNum = 0;
            if (goods.getGiftRules() != null && !goods.getGiftRules().isEmpty()) {
                for (GiftRule rule : goods.getGiftRules()) {
                    if (num >= rule.getBuyNum()) {
                        giftNum = rule.getGiftNum();
                        break;
                    }
                }
            }
            
            return cartMapper.updateNum(id, userId, num, giftNum) > 0;
        } catch (Exception e) {
            logger.error("Error updating cart num: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }
    
    @Transactional
    public boolean updateSelected(Long id, Long userId, Integer selected) {
        logger.info("Updating cart selected: id={}, userId={}, selected={}", id, userId, selected);
        try {
            if (selected != 0 && selected != 1) {
                logger.warn("Invalid selected value: {}, setting to 1", selected);
                selected = 1;
            }
            return cartMapper.updateSelected(id, userId, selected) > 0;
        } catch (Exception e) {
            logger.error("Error updating cart selected: ", e);
            throw new RuntimeException("Failed to update cart selected: " + e.getMessage());
        }
    }
    
    @Transactional
    public boolean deleteCart(Long id, Long userId) {
        logger.info("Deleting cart: id={}, userId={}", id, userId);
        try {
            return cartMapper.delete(id, userId) > 0;
        } catch (Exception e) {
            logger.error("Error deleting cart: ", e);
            throw new RuntimeException("Failed to delete cart: " + e.getMessage());
        }
    }
    
    @Transactional
    public Order checkout(Long userId) {
        try {
            // 1. 获取用户地址
            List<Address> addresses = addressMapper.findByUserId(userId);
            if (addresses.isEmpty()) {
                throw new RuntimeException("请先添加收货地址");
            }
            Address address = addresses.get(0);  // 获取用户唯一的地址
            
            // 2. 获取购物车选中的商品
            List<Cart> cartList = cartMapper.findByUserId(userId);
            List<Cart> selectedCarts = cartList.stream()
                    .filter(cart -> cart.getSelected() == 1)
                    .collect(Collectors.toList());
            
            if (selectedCarts.isEmpty()) {
                throw new RuntimeException("请选择要结算的商品");
            }
            
            // 3. 创建订单
            Order order = new Order();
            order.setOrderNo(generateOrderNo());
            order.setUserId(userId);
            order.setAddressId(address.getId());
            order.setStatus(1);  // 1: 待付款
            
            // 4. 处理订单商品
            List<OrderGoods> orderGoodsList = new ArrayList<>();
            BigDecimal totalPrice = BigDecimal.ZERO;
            
            for (Cart cart : selectedCarts) {
                // 获取商品信息
                Goods goods = goodsMapper.findById(cart.getGoodsId());
                if (goods == null || goods.getStatus() != 1) {
                    throw new RuntimeException("商品" + cart.getGoodsTitle() + "已下架");
                }
                
                // 检查库存
                int totalNum = cart.getNum() + cart.getGiftNum();
                if (totalNum > goods.getStock()) {
                    throw new RuntimeException("商品" + cart.getGoodsTitle() + "库存不足");
                }
                
                // 创建订单商品
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setGoodsId(cart.getGoodsId());
                orderGoods.setGoodsTitle(cart.getGoodsTitle());
                orderGoods.setGoodsImage(goods.getCoverImage());
                orderGoods.setGoodsPrice(goods.getPrice());
                orderGoods.setNum(cart.getNum());
                orderGoods.setGiftNum(cart.getGiftNum());
                orderGoods.setTotalPrice(goods.getPrice().multiply(new BigDecimal(cart.getNum())));
                
                // 设置赠送规则文本
                if (goods.getGiftRules() != null && !goods.getGiftRules().isEmpty()) {
                    StringBuilder giftRuleText = new StringBuilder();
                    for (GiftRule rule : goods.getGiftRules()) {
                        if (giftRuleText.length() > 0) {
                            giftRuleText.append("；");
                        }
                        giftRuleText.append(String.format("满%d件送%d件", rule.getBuyNum(), rule.getGiftNum()));
                    }
                    orderGoods.setGiftRuleText(giftRuleText.toString());
                }
                
                orderGoodsList.add(orderGoods);
                totalPrice = totalPrice.add(orderGoods.getTotalPrice());
            }
            
            order.setTotalPrice(totalPrice);
            
            // 5. 保存订单
            orderMapper.insert(order);
            
            // 6. 保存订单商品
            for (OrderGoods orderGoods : orderGoodsList) {
                orderGoods.setOrderId(order.getId());
                orderGoodsMapper.insert(orderGoods);
            }
            
            // 7. 删除已结算的购物车商品
            for (Cart cart : selectedCarts) {
                cartMapper.delete(cart.getId(), userId);
            }
            
            // 8. ��回完整的订单信息（包含地址和商品详情）
            return orderMapper.findById(order.getId(), userId);
            
        } catch (Exception e) {
            logger.error("Checkout failed: ", e);
            throw new RuntimeException(e.getMessage());
        }
    }
    
    // 生成订单号
    private String generateOrderNo() {
        return String.format("%s%06d", 
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                (int)(Math.random() * 1000000));
    }
} 